package yxxy;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 循环屏障
 * @author zl
 *
 */
public class CyclicBarrierTest {
	public static void main(String[] args) {
//		final CyclicBarrier cb = new CyclicBarrier(3);
		final CyclicBarrier cb = new CyclicBarrier(3,new Runnable() {

			@Override
			public void run() {
				// TODO 
				System.out.println("人员全部到齐，各自拍照");
				try {
					Thread.sleep((long)(Math.random()*10000));
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		});
		ExecutorService threadPool = Executors.newCachedThreadPool();
		for(int i = 0; i<3;i++) {
			final int user = i+1;
			Runnable r = new Runnable() {

				@Override
				public void run() {
					try {
						// TODO 模拟每个人到达屏障时间
						Thread.sleep((long)(Math.random()*10000));
						System.out.println(user+"到达聚餐地点，当前已有"
						+(cb.getNumberWaiting()+1)+"人");
						//障碍物
						cb.await();
						if(user==1) {
							System.out.println("拍照结束，开始吃饭");
						}

						Thread.sleep((long)(Math.random()*10000));
						System.out.println(user+"吃完饭，准备离开");
					}catch( Exception e) {
						e.printStackTrace();
					}
				}
				
			};
			threadPool.execute(r);
		}
		threadPool.shutdown();
	}
}
